package com.yonyou.pmclouds.outter.user;

import java.io.IOException;
import java.util.*;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.yonyou.iuap.tenant.sdk.UserCenter;
import com.yonyou.iuap.tenant.utils.TenantSdkPropertyUtil;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yonyou.iuap.tenant.sdk.UserRoleCenter;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.user.entity.UserInfo;

import lombok.extern.log4j.Log4j;

@Log4j
@Component
public class UserOperator {


    private ObjectMapper objectMapper;

    public UserOperator() {
        objectMapper = new ObjectMapper();
        //忽略未识别字段
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    /**
     *
     * 给用户分配角色。
     *
     * <b>参数说明</b>
     * @param userId
     * @param pk_tenant
     * @param roleMapList List<Map> 每一个map需要包含roleId 和 roleCode
     * @throws BusinessException
     * @author zhangwce
     * @time 2018年1月25日 下午9:59:28
     */
    public void userAddRole(String userId,String pk_tenant,List<Map> roleMapList ) throws BusinessException{

        String addRoleInfo = buildAddRoleInfo(userId, pk_tenant, roleMapList);

        Date beginDate = new Date();
        String userRoleResult = UserRoleCenter.userAddRole(addRoleInfo);
        if(StringUtils.isEmpty(userRoleResult)){
            log.error("用户分配权限失败，错误信息为：友户通服务异常" );
            throw new BusinessException("用户分配权限失败，错误信息为：友户通服务异常");
        }
        log.error("访问外部接口，用户分配角色耗时："+ (new Date().getTime() - beginDate.getTime()));
        Map userRoleResultMap = null;
        try {
            userRoleResultMap = objectMapper.readValue(userRoleResult, Map.class);
        } catch (Exception e) {
            log.error(e.getMessage());
        }

        if (Integer.valueOf(0).equals(userRoleResultMap.get("status"))) {
            String errMsg = (String) userRoleResultMap.get("msg");
            log.error("用户分配权限失败，错误信息为：" + errMsg);
            throw new BusinessException(errMsg);
        }

    }

    /**
     *
     * 方法功能描述：构造传入的用户角色信息。
     *
     * <b>参数说明</b>
     * @param userId
     * @param pk_tenant
     * @param roleMapList
     * @return
     * @throws BusinessException
     * @author zhangwce
     * @time 2018年1月25日 下午10:02:56
     */
    private String buildAddRoleInfo(String userId, String pk_tenant, List<Map> roleMapList) throws BusinessException {
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("userId", userId);
        UserInfo userInfo = new UserInfoQuery().queryUser(userId);
        if(userInfo == null ){
            log.error("用户分配权限失败，错误信息为：未根据用户ID找到用户code" );
            throw new BusinessException("用户分配权限失败");
        }

        queryMap.put("userCode", userInfo.getUserCode());
        queryMap.put("tenantId", pk_tenant);
        queryMap.put("roles", roleMapList);

        String addRoleInfo = null;
        try {
            addRoleInfo = objectMapper.writeValueAsString(queryMap);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return addRoleInfo;
    }

    /**
     * 给用户发送邮件
     *
     * @param userId
     * @param message
     * @param title
     * @param isHtml
     */
    public void sendMsgByEmail(String userId,String message,String title,boolean isHtml){
        UserCenter.sendMsgByEmail(userId,message,title,isHtml);
    }

    /**
     * 根据用户id查询用户角色
     */
    public Map queryRoleByUserId(String pkTenant, String userId) throws IOException {
        String userRole = UserRoleCenter.queryRoleByUser(userId, pkTenant, TenantSdkPropertyUtil.getPropertyByKey("sysid"));
        return objectMapper.readValue(userRole, Map.class);
    }

    public List<String> getPkRoles(String tenantId, String userId) throws IOException {
        List<String> pkRoles = new ArrayList<>();
        Map map = this.queryRoleByUserId(tenantId, userId);
        if (map != null && map.get("data") != null){
            pkRoles = (ArrayList) map.get("data");
        }

        return pkRoles;
    }

}
